package com.catazy.jetpackstudy.act2.chapter4.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @作者: Tao
 * @日期: 2025/2/8
 * @时间: 10:31
 * @描述: BookProvider - 自定义ContentProvider
 */
public class BookProvider extends ContentProvider {

    public static final String AUTHORITY = "com.catazy.jetpackstudy.act2.chapter4.contentprovider";
    public static final String BOOK_URI_CONTENT = "content://" + AUTHORITY + "/book";
    public static final String USER_URI_CONTENT = "content://" + AUTHORITY + "/user";
    public static final int BOOK_URI_CODE = 0;
    public static final int USER_URI_CODE = 1;

    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(AUTHORITY, "book", BOOK_URI_CODE);
        uriMatcher.addURI(AUTHORITY, "user", USER_URI_CODE);
    }

    private Context mContext;
    private DbOpenHelper mDbOpenHelper;
    private SQLiteDatabase mDb;

    @Override
    public boolean onCreate() {
        Log.d("BookProvider", "onCreate, current thread: " + Thread.currentThread().getName());
        mContext = getContext();
        mDbOpenHelper = new DbOpenHelper(mContext);
        initProviderData();
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Log.d("BookProvider", "query, current thread: " + Thread.currentThread().getName());
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("Unsupported Uri: " + uri);
        }

        return mDb.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        Log.d("BookProvider", "getType, current thread: " + Thread.currentThread().getName());
        return "";
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        Log.d("BookProvider", "insert, current thread: " + Thread.currentThread().getName());
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("Unsupported Uri: " + uri);
        }

        mDb.insert(tableName, null, values);
        mContext.getContentResolver().notifyChange(uri, null);
        return uri;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.d("BookProvider", "delete, current thread: " + Thread.currentThread().getName());
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("Unsupported Uri: " + uri);
        }
        int count = mDb.delete(tableName, selection, selectionArgs);
        if (count > 0) {
            mContext.getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.d("BookProvider", "update, current thread: " + Thread.currentThread().getName());
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("Unsupported Uri: " + uri);
        }

        int count = mDb.update(tableName, values, selection, selectionArgs);
        if (count > 0) {
            mContext.getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public void shutdown() {
        super.shutdown();
        if (mDb != null && mDb.isOpen()) {
            mDb.close();
        }
        if (mDbOpenHelper != null) {
            mDbOpenHelper.close();
        }
    }

    private void initProviderData() {
        try {
            mDb = mDbOpenHelper.getWritableDatabase();
            mDb.execSQL("delete from " + DbOpenHelper.BOOK_TABLE_NAME);
            mDb.execSQL("delete from " + DbOpenHelper.USER_TABLE_NAME);
            mDb.execSQL("insert into book values(3, 'Android');");
            mDb.execSQL("insert into book values(4, 'Java');");
            mDb.execSQL("insert into book values(5, 'C++');");
            mDb.execSQL("insert into user values(1, 'Tao', 31);");
            mDb.execSQL("insert into user values(2, 'Zhang', 30);");
            mDb.execSQL("insert into user values(3, 'Li', 29);");
        } catch (Exception e) {
            Log.d("BookProvider", "initProviderData error: " + e.getMessage());
        }
    }


    /**
     * 根据Uri匹配表名
     *
     * @param uri Uri
     * @return 表名
     */
    private String getTableName(Uri uri) {
        String tableName = null;
        switch (uriMatcher.match(uri)) {
            case BOOK_URI_CODE:
                tableName = DbOpenHelper.BOOK_TABLE_NAME;
                break;
            case USER_URI_CODE:
                tableName = DbOpenHelper.USER_TABLE_NAME;
                break;
            default:
                break;
        }
        return tableName;
    }
}
